﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Net;
using System.Text;

namespace EntityModule
{
    public class RSSHelper
    {
        public class RssNews
        {
            public string Title;
            public string PublicDate;
            public string Description;
            public string Link;
        }
        public static void Start()
        {
            string URL = System.Configuration.ConfigurationSettings.AppSettings["URLRSS"].AsString();
            int mintue = System.Configuration.ConfigurationSettings.AppSettings["MinuteRepeart"].AsInt();
            Insert(URL);
            /* while (true)
             {
                 Insert(URL);
             }*/
        }
        
        public static void Insert(string url)
        {
            List<RssNews> rss = Read(url);
            foreach (RssNews rssNewse in rss)
            {
                New news = new New
                    {
                        Tilte = rssNewse.Title,
                        Body = rssNewse.Description,
                        Link = rssNewse.Link,
                        DateModifier = rssNewse.PublicDate.AsDate()
                    };
                NewsDetail detail = new NewsDetail
                   {
                       ID = Guid.NewGuid(),
                       New = news,
                       Body = HtmlHelper.GetInnerHtmlDiv("content_news", rssNewse.Link),
                       DateModifier = rssNewse.PublicDate.AsDate()
                   };
                new NewsService().Insert(news);
            }
        }
        public static List<RssNews> Read(string url)
        {
            var webResponse = WebRequest.Create(url).GetResponse();
            if (webResponse == null)
                return null;
            var ds = new DataSet();
            ds.ReadXml(webResponse.GetResponseStream());
            DataTable table = ds.Tables["item"];
            var news = (from row in table.AsEnumerable()
                        select new RssNews
                        {
                            Title = row.Field<string>("title"),
                            Link = row.Field<string>("Link"),
                            PublicDate = ds.Tables["channel"].Rows[0]["PubDate"].ToString(),
                            Description = row.Field<string>("description")
                        }).ToList();
            return news;
        }
    }
}
